<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="el-icon-document">发起任务</span>
        <el-button style="float: right;" size="default" type="danger" @click="goBack">关闭</el-button>
      </div>
      <el-tabs tab-position="top" v-model="activeName" @tab-click="handleClick">
        <!-- 表单信息 -->
        <el-tab-pane label="表单信息" name="1">
          <!-- 初始化流程加载表单信息 -->
          <el-col :span="16" :offset="4">
            <v-form-render :form-data="formRenderData" ref="vFormRef" />
            <div style="margin-left:15%; margin-bottom: 20px; font-size: 14px;">
              <el-button type="primary" @click="submitForm">提 交</el-button>
              <el-button type="primary" @click="resetForm">重 置</el-button>
            </div>
          </el-col>
        </el-tab-pane>
        <!-- 流程图 -->
        <el-tab-pane label="流程图" name="2">
          <bpmn-viewer :flow-data="flowData" />
        </el-tab-pane>
      </el-tabs>
      <!-- 选择流程接收人 -->
      <el-dialog :title="taskTitle" v-model="taskOpen" width="65%" append-to-body>
        <flow-user v-if="checkSendUser" :check-type="checkType" @handleUserSelect="handleUserSelect" />
        <flow-role v-if="checkSendRole" @handleRoleSelect="handleRoleSelect" />
        <template #footer>
          <el-button @click="taskOpen = false">取 消</el-button>
          <el-button type="primary" @click="submitTask">提 交</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { definitionStart, flowXmlAndNode } from '@/api/flowable/definition';
import {flowFormData} from "@/api/flowable/process";
import {getNextFlowNodeByStart} from "@/api/flowable/todo";
import BpmnViewer from '@/components/Process/viewer';
import FlowUser from '@/components/flow/User';
import FlowRole from '@/components/flow/Role';

const vFormRef = ref(null);
const route = useRoute();
const router = useRouter();

const activeName = ref('1');
const flowData = ref({});
const deployId = ref('');
const procDefId = ref('');
const formRenderData = ref({});
const variables = reactive([]);
const taskTitle = ref(null);
const taskOpen = ref(false);
const checkSendUser = ref(false);
const checkSendRole = ref(false);
const checkType = ref('');
const checkValues = ref(null);
const formData = reactive({});
const multiInstanceVars = ref('');
const formJson = ref({});

const handleClick = (tab) => {
  if (tab.props.name === '2') {
    flowXmlAndNode({ deployId: deployId.value }).then((res) => {
      flowData.value = res.data;
    });
  }
};
/** 流程表单数据 */
const getFlowFormData = (deployIdParam) => {
  const params = { deployId: deployIdParam };
  flowFormData(params).then((res) => {
    // 流程过程中不存在初始化表单 直接读取的流程变量中存储的表单值
    nextTick(() => {
      // 回显数据
      vFormRef.value.setFormJson(res.data);
      formJson.value = res.data;
    });
  }).catch(() => {
    goBack();
  });
};
/** 返回页面 */
const goBack = () => {
  // 关闭当前标签页并返回上个页面
  const obj = { path: "/task/process", query: { t: Date.now() } };
  router.push(obj);
};
/** 申请流程表单数据提交 */
const submitForm = () => {
  vFormRef.value.getFormData().then((formData) => {
    // 根据当前任务或者流程设计配置的下一步节点 todo 暂时未涉及到考虑网关、表达式和多节点情况
    getNextFlowNodeByStart({ deploymentId: deployId.value, variables: formData }).then((res) => {
      const data = res.data;
      // console.log('data--------------->', data)
      if (data) {
        Object.assign(formData, formData);
        if (data.dataType === 'dynamic') {
          if (data.type === 'assignee') {
            checkSendUser.value = true;
            checkType.value = "single";
          } else if (data.type === 'candidateUsers') {
            checkSendUser.value = true;
            checkType.value = "multiple";
          } else if (data.type === 'candidateGroups') {
            checkSendRole.value = true;
          } else {
            multiInstanceVars.value = data.vars;
            checkSendUser.value = true;
            checkType.value = "multiple";
          }
          taskOpen.value = true;
          taskTitle.value = "选择任务接收";
        } else {
          if (procDefId.value) {
            const param = { formJson: formJson.value };
            Object.assign(param, formData);
            definitionStart(procDefId.value, param).then((res) => {
              ElMessage.success(res.msg);
              goBack();
            });
          }
        }
      }
    });
  }).catch((error) => {
    console.error(error);
  });
};

const resetForm = () => {
  vFormRef.value.resetForm();
};

const submitTask = () => {
  if (!checkValues.value && checkSendUser.value) {
    ElMessage.error("请选择任务接收!");
    return;
  }
  if (!checkValues.value && checkSendRole.value) {
    ElMessage.error("请选择流程接收角色组!");
    return;
  }
  if (Object.keys(formData).length > 0) {
    const param = { formJson: formJson.value };
    Object.assign(param, formData);
    if (multiInstanceVars.value) {
      param[multiInstanceVars.value] = checkValues.value;
    } else {
      param.approval = checkValues.value;
    }
    definitionStart(procDefId.value, param).then((res) => {
      ElMessage.success(res.msg);
      goBack();
    });
  }
};

const handleUserSelect = (selection) => {
  if (selection) {
    if (Array.isArray(selection)) {
      const selectVal = selection.map((item) => item.userId);
      if (multiInstanceVars.value) {
        checkValues.value = selectVal;
      } else {
        checkValues.value = selectVal.join(',');
      }
    } else {
      checkValues.value = selection.userId;
    }
  }
};

const handleRoleSelect = (selection) => {
  if (selection) {
    if (Array.isArray(selection)) {
      const selectVal = selection.map((item) => item.roleId);
      checkValues.value = selectVal.join(',');
    } else {
      checkValues.value = selection;
    }
  }
};

onMounted(() => {
  deployId.value = route.query.deployId;
  procDefId.value = route.query.procDefId;
  getFlowFormData(deployId.value);
});
</script>

<style lang="scss" scoped>
.test-form {
  margin: 15px auto;
  width: 800px;
  padding: 15px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.my-label {
  background: #E1F3D8;
}
</style>